import numpy as np
import pandas as pd
import subprocess

# LIONESS
def lioness(data, i):
    # Construct sample specific network

    corr_all = np.corrcoef(data)
    v0 = pd.DataFrame.drop(data, i, axis=1)
    corr_single = np.corrcoef(v0)
    x = data.shape[1] * (corr_all - corr_single) + corr_single
    x[np.isnan(x)] = 0

    m_x = np.max(np.abs(x[x != 0]))
    x = x/m_x
    np.fill_diagonal(x, 1)
    
    corrnet = x

    return corrnet
  
  
# Single Pearson Correlation Coefficient
def spcc(data, i):
    # Construct sample specific network
    
    mean_all = np.mean(data, axis=1)
    sd_all = np.std(data, axis=1)
    v = data.iloc[:, i]
    x = (v - mean_all) / sd_all
    x[np.isnan(x)] = 0
    x[np.abs(x) == np.inf] = 0

    prod = np.outer(x, x)
    x = prod

    m_x = np.max(np.abs(x[x != 0]))
    x = x/m_x
    np.fill_diagonal(x, 1)
    
    corrnet = x

    return corrnet
  

# SWEET
def sweet(data):
  expression = pd.DataFrame(np.array(data).transpose())
  # Save expression data
  expression.to_csv('./SWEET_main/simulation_sweet/simulated_expression.txt', sep='\t', mode='w')
  # Save column (individuals) and row (genes) indices
  individuals = expression.axes[1].tolist()
  genes = expression.axes[0].tolist()
  with open('./SWEET_main/simulation_sweet/individuals.txt', 'w') as f:
    for line in individuals:
      f.write(f"{line}\n")
      
      
  with open('./SWEET_main/simulation_sweet/genes.txt', 'w') as f:
    for line in genes:
      f.write(f"{line}\n")
      
      
  command = 'python3 ./SWEET_main/1.SWEET_sample_weight_calculating.py -f ./SWEET_main/simulation_sweet/simulated_expression.txt -s ./SWEET_main/simulation_sweet/outputs/simulated_weight.txt'
  process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
  output, error = process.communicate()

  command = 'python3 ./SWEET_main/2.SWEET_edge_score_calculating.py -f ./SWEET_main/simulation_sweet/simulated_expression.txt -w ./SWEET_main/simulation_sweet/outputs/simulated_weight.txt -p ./SWEET_main/simulation_sweet/individuals.txt -g ./SWEET_main/simulation_sweet/genes.txt -s ./SWEET_main/simulation_sweet/outputs'
  process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
  output, error = process.communicate()
  
  command = 'python3 ./SWEET_main/3.SWEET_calculating_mean_std_zscore.py -p ./SWEET_main/simulation_sweet/individuals.txt -l  ./SWEET_main/simulation_sweet/outputs -s ./SWEET_main/simulation_sweet/outputs/mean_std.txt -z True'
  process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
  output, error = process.communicate()
  
  
  
